package com.epfresh.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.epfresh.R;
import com.epfresh.adapter.*;
import com.epfresh.api.constant.AppPurchaseRouterConstant;
import com.epfresh.api.entity.*;
import com.epfresh.api.entity.RequestTag;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.http.HttpRequest;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.widget.list.LoadMoreListView;
import com.epfresh.api.widget.ptr.PtrDefaultHandler;
import com.epfresh.api.widget.ptr.PtrFrameLayout;
import com.epfresh.api.widget.ptr.PtrHandler;
import com.epfresh.api.widget.ptr.PtrMdFrameLayout;
import com.epfresh.bean.ContentEntity;
import com.epfresh.bean.ListStore;
import com.epfresh.constant.Constant;
import com.epfresh.global.BaseActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import multitype.OnRecyclerViewItemClickListener;

public class RecyclerListStoreActivity extends BaseActivity {
    private RecyclerView mListView;
    private RelativeLayout nodate_ll;
    private TextView nodate_hint;
    private ArrayList<ArrayList<ListStore>> newList = new ArrayList<>();
    Context mContext;
    int page=0; //加载页码控制 从0开始
    StoreRecyclerListAdapter adapter;
    String cgiName= "store/list";

    String favorite="";
    String marketId="",areaId="";

    String searchKey;


    boolean firstFlag = true;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        mListView = (RecyclerView) findViewById(R.id.listview);
        mContext = this;
        adapter = new StoreRecyclerListAdapter();
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mListView.setLayoutManager(layoutManager);


        mListView.setAdapter(adapter);

        adapter.setOnRecyclerViewItemClickListener(new OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int i, Object o) {
                toast("点击了大概第几个？"+i);
            }
        });
        adapter.setCategory(newList);

        //adapter.setOnItemClickListener(this);
        nodate_hint.setText("暂无店铺！");
        searchKey = getIntent().getStringExtra("searchKey");
        if (getIntent().getStringExtra("name") != null) {
            basetitle.setText(getIntent().getStringExtra("name"));
            if("我的关注".equals(getIntent().getStringExtra("name"))){
                nodate_hint.setText("暂无店铺关注！");
                favorite = "true";
            }else{
                marketId = getIntent().getStringExtra("marketId");
                areaId = getIntent().getStringExtra("areaId");
            }
        }else{
            basetitle.setText("新店推荐");
        }

        baseback.setVisibility(View.VISIBLE);
        requestOrderList(0);
    }

    void initView(){
        setContentView(R.layout.activity_recycler_list);
        nodate_hint = (TextView)findViewById(R.id.nodate_hint);
        nodate_ll = (RelativeLayout)findViewById(R.id.nodate_ll);
    }
    private PtrMdFrameLayout ptrFrameLayout;
    private PtrHandler ptrHandler = new PtrHandler() {
        @Override
        public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
            return PtrDefaultHandler.checkContentCanBePulledDown(frame, mListView, header);
        }

        @Override
        public void onRefreshBegin(PtrFrameLayout frame) {
        }
    };

    boolean mLastFlag = false;
    //当前分页
    private int currentPage = 0;
    //期望的分页
    private int expectPage = 0;
    private RequestTag requestTag = new RequestTag();

    public void requestOrderList(int page) {

/*        SharedPreferences user = getSharedPreferences(
                Constant.USERINFO, Activity.MODE_PRIVATE);*/
        RequestEntityPurchase<Map<String, Object>> entity = new RequestEntityPurchase<>();
        Map<String, Object> map = new HashMap<>();
        map.put("name",searchKey);
        map.put("marketId", marketId);
        map.put("areaId", areaId);
        map.put("favorite",favorite);
        map.put("pageNumber", page + "");
        map.put("pageSize", 30 + "");
        map.put("sortProperty", "name");
        map.put("sortDirection", "DESC");
        entity.setCmd(AppPurchaseRouterConstant.cmd_store_store_list);
        entity.setParameters(map);
        requestTag.tag = AppPurchaseRouterConstant.cmd_store_store_list;
        requestTag.action = page;
        request(entity, requestTag, onRequestListener);

    }

    OnRequestListener<ContentEntity<ListStore>> onRequestListener = new OnRequestListener<ContentEntity<ListStore>>() {
        @Override
        public ContentEntity<ListStore> jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, new TypeToken<ContentEntity<ListStore>>() {
            }.getType());
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();
            updateView(tag);
            switch (failCode) {
                case HttpRequest.FAIL_NOT_FOUND:
                    showExceptionView(0, null, 0);
                    break;
                case HttpRequest.FAIL_NO_NET:
                    showExceptionView(0, null, 0);
                    break;
                case HttpRequest.FAIL_NET_FAULT:
                    showExceptionView(0, null, 0);
                default:
                    showExceptionView(0, null, 0);
                    //showReload();
                    break;
            }
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            updateView(tag);
            showMainView();
        }

        @Override
        public void onStart(Object tag) {
            if(firstFlag==true){
                firstFlag = false;
                showProgressDialog();
            }
            nodate_ll.setVisibility(View.GONE);
            mListView.setVisibility(View.VISIBLE);
        }

        @Override
        public void onResponse(ResponseEntity<ContentEntity<ListStore>> response, Object tag) {
            hideProgressDialog();
            showMainView();
            ContentEntity<ListStore> goodsResponse = response.getResponseElement();
            List<ListStore> content = goodsResponse.getContent();
            currentPage = goodsResponse.getNumber();
            mLastFlag = goodsResponse.getLast();
            boolean isRefresh = updateView(tag);
            if (content != null && content.size() > 0) {

                ArrayList<ArrayList<ListStore>> newFlag = new ArrayList<>();//(content.size()+1)/2);
                for(int i=0;i<(content.size()+1)/2;i++){
                    ArrayList<ListStore> flag = new ArrayList<>();
                    flag.add(content.get(2*i));
                    if (content.size() > 2 * i + 1) {
                        flag.add(content.get(2 * i + 1));
                    }
                    newFlag.add(flag);
                    Log.e("flagList____size",""+newFlag.size());

                }
                newList.addAll(newFlag);
                Log.e("newList____size",""+newList.size());
                adapter.notifyDataSetChanged();

/*                list.addAll(content);
                adapter.notifyDataSetChanged();*/




            } else {
                nodate_ll.setVisibility(View.VISIBLE);
                mListView.setVisibility(View.GONE);
                //没有数据
            }


        }
    };

    private boolean updateView(Object tag) {
        return false;
    }


    public void onClick(View v) {
        int position;
        switch (v.getId()) {
            case R.id.baseback:
                // 返回上一页
                finish();
                break;
            case R.id.nodate_start:

//                refresh();
                break;
            case R.id.iv_phone:
                position = (Integer)v.getTag(R.id.item_key_position);

                Intent call = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + newList.get(position/10).get(position%10).getManagerPhone()));//调出来拨打页面；
                startActivity(call);
                break;
            case R.id.v_1:
            case R.id.v_2:
                position = (Integer)v.getTag(R.id.item_key_position);
                Intent storeIntent = new Intent(this,
                        CommonStoreActivity.class);
                storeIntent.putExtra("storeId", newList.get(position/10).get(position%10).getId());
                startActivity(storeIntent);
                break;


        }
    }
}
